import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Form, message, Select, Upload, Button, Input } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import _ from 'loadsh'
import { Line, Cell, Split } from '@components/ApprovePre/Approve'
import CaseArbitratorSelector from '@components/CaseArbitratorSelector/Index'
import { getArbitratorList, getDictinarys } from '../ajax'
import { awaitWrap, getUploadProps } from '@js/tool'
const { TextArea } = Input
const { Item } = Form
const { Option, OptGroup } = Select
export default class StepOneInput extends Component {
  state = {
    keyTitleMap: {},
    fileList: [],
    submitOptions: {},
    arbitrators: [],
    dictionaries: {}
  }

  initKeyTitleMap () {
    const map = {}
    const list = _.get(this.props.instance || {}, 'currentStep.vars', [])
    list.forEach(li => {
      map[li.key] = li.title
    })
    this.setState({
      keyTitleMap: map
    })
  }

  // 获取仲裁员列表
  async getArbitratorList () {
    const [e, d] = await awaitWrap(getArbitratorList(this.props.caseDetail.id))
    if (e) {
      return message.warning(e.message)
    }
    this.setState({
      arbitrators: d
    }, () => {
      this.initSubmitOptions()
    })
  }

  initSubmitOptions () {
    const d = this.props.caseDetail || {}
    const applicants = d.applicants || []
    const applicantAgents = d.applicant_agents || []
    const respondents = d.respondents || []
    const respondentAgents = d.respondents_agents || []
    const arbitrators = this.state.arbitrators || []
    this.setState({
      submitOptions: {
        申请人: applicants,
        申请人代理人: applicantAgents,
        被申请人: respondents,
        被申请人代理人: respondentAgents,
        仲裁员: arbitrators
      }
    })
  }

  // 改变提出人
  changeSubmital (ids) {
    const c = this.props.formRef.current
    const names = []
    const o = this.state.submitOptions
    const keys = Object.keys(o)
    let list = []
    keys.forEach(k => {
      list = [...list, ...o[k]]
    })
    const listIds = list.map(li => li.id)
    ids.forEach(id => {
      const index = listIds.indexOf(id)
      if (index !== -1) {
        names.push(list[index].name)
      }
    })
    const vars = c.getFieldValue(['vars'])
    c.setFieldsValue({
      vars: {
        ...vars,
        challenge_submittal: names.join()
      }
    })
  }

  // 初始化字典
  async initDictionary () {
    const [e, d] = await awaitWrap(getDictinarys(['仲裁地位', '回避退出类型', '回避情形']))
    if (e) {
      return message.warning(e.message)
    }
    this.setState({
      dictionaries: d
    })
  }

  componentDidUpdate (prev) {
    if (this.props.instance !== prev.instance) {
      this.initKeyTitleMap()
      this.getArbitratorList()
    }
  }

  componentDidMount () {
    this.initDictionary()
    this.initKeyTitleMap()
    this.getArbitratorList()
  }

  // 渲染提出人可选项
  renderSubmitalOptions () {
    const o = this.state.submitOptions
    let keys = Object.keys(o)
    keys = keys.filter(k => o[k].length)
    return keys.map(k => {
      const l = o[k]
      return (
        <OptGroup key={k} label={k}>
          {l.map(li => {
            return (
              <Option key={li.id} value={li.id}>{li.name}</Option>
            )
          })}
        </OptGroup>
      )
    })
  }

  render () {
    const { keyTitleMap, dictionaries } = this.state
    const caseid = this.props.caseDetail.id
    const identityList = dictionaries['仲裁地位'] || []
    const avoidTypeList = dictionaries['回避退出类型'] || []
    const avoidList = dictionaries['回避情形'] || []
    return (
      <div>
        <Line>
          <Cell>
            <Item labelCol={{ flex: '100px' }} label='操作者'>
              <span>{this.props.userInfo.realname}</span>
            </Item>
          </Cell>
        </Line>
        <Line>
          <Cell>
            <Item name={['vars', 'challenge_submittal']} noStyle><span /></Item>
            <Item labelCol={{ flex: '100px' }} name={['vars', 'challenge_submittalid']} label={keyTitleMap.challenge_submittal} rules={[{ required: true, message: `${keyTitleMap.challenge_submittal}不能为空` }]}>
              <Select placeholder='请选择' mode='multiple' onChange={e => this.changeSubmital(e)} maxTagTextLength={10}>
                {this.renderSubmitalOptions()}
              </Select>
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item labelCol={{ flex: '130px' }} name={['vars', 'challenge_submittal_type']} label={keyTitleMap.challenge_submittal_type} rules={[{ required: true, message: `${keyTitleMap.challenge_submittal_type}不能为空` }]}>
              <Select placeholder='请选择' allowClear>
                {identityList.map((li, i) => {
                  return (
                    <Option key={i} value={li.value}>{li.title}</Option>
                  )
                })}
              </Select>
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item labelCol={{ flex: '100px' }} name={['vars', 'challenge_challenged']} label={keyTitleMap.challenge_challenged} rules={[{ required: true, message: `${keyTitleMap.challenge_challenged}不能为空` }]}>
              <CaseArbitratorSelector caseid={caseid} mode='multiple' />
            </Item>
          </Cell>
        </Line>
        <Line>
          <Cell>
            <Item labelCol={{ flex: '100px' }} name={['vars', 'challenge_type']} label={keyTitleMap.challenge_type} rules={[{ required: true, message: `${keyTitleMap.challenge_type}不能为空` }]}>
              <Select placeholder='请选择' allowClear>
                {avoidTypeList.map((li, i) => {
                  return (
                    <Option key={i} value={li.value}>{li.title}</Option>
                  )
                })}
              </Select>
            </Item>
          </Cell>
          <Split />
          <Cell>
            <Item name='file' labelCol={{ flex: '130px' }} label={keyTitleMap.challenge_fileid}>
              <Upload {...getUploadProps.call(this, this.props.formRef)}>
                <Button disabled={this.state.fileList.length !== 0}>
                  <UploadOutlined /> 上传文件
                </Button>
              </Upload>
            </Item>
          </Cell>
        </Line>
        <Line>
          <Cell style={{ width: '65%' }}>
            <Item labelCol={{ flex: '100px' }} name={['vars', 'challenge_circumstance']} label={keyTitleMap.challenge_circumstance} rules={[{ required: true, message: `${keyTitleMap.challenge_circumstance}不能为空` }]}>
              <Select placeholder='请选择' allowClear>
                {avoidList.map((li, i) => {
                  return (
                    <Option key={i} value={li.value}>{li.title}</Option>
                  )
                })}
              </Select>
            </Item>
          </Cell>
        </Line>
        <Line>
          <Cell style={{ width: '65%' }}>
            <Item labelCol={{ flex: '100px' }} name={['vars', 'challenge_remark']} label={keyTitleMap.challenge_remark} rules={[{ required: true, message: `${keyTitleMap.challenge_remark}不能为空` }]}>
              <TextArea placeholder='请输入' autoSize={{ minRows: 2 }} />
            </Item>
          </Cell>
        </Line>
      </div>
    )
  }
}

StepOneInput.proptypes = {
  caseDetail: PropTypes.object,
  userInfo: PropTypes.object,
  instance: PropTypes.object,
  formRef: PropTypes.object,
  dictionaries: PropTypes.object
}

StepOneInput.defaultProps = {
  caseDetail: {},
  userInfo: {},
  instance: {},
  formRef: {},
  dictionaries: {}
}
